//
//  AccountDownloadVC.m
//  ImGuider
//
//  Created by llt on 2017/5/12.
//  Copyright © 2017年 imguider. All rights reserved.
//

#import "AccountDownloadVC.h"
#import "ScenicGuiderListCell.h"
#import "DownloadListDAO.h"
#import "ScenicPlayVC.h"
#import "CityTourPlay.h"
#import "PlayerItem.h"

#import "AccountDownloadCell.h"

@interface AccountDownloadVC ()<UITableViewDataSource, UITableViewDelegate>

@property (weak, nonatomic) IBOutlet UITableView *tableView;

@property (weak, nonatomic) IBOutlet UIView *bottomView;

@property (weak, nonatomic) IBOutlet UIButton *totalDeleteBtn;
@property (weak, nonatomic) IBOutlet UIButton *totalSelectBtn;
@property (weak, nonatomic) IBOutlet UIButton *cancelBtn;

@property (nonatomic, copy) NSMutableArray *dataSource;
@property (nonatomic, copy) NSMutableArray *deleteArray;

@end

@implementation AccountDownloadVC

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setup];
}

- (NSMutableArray *)dataSource {
    
    if (!_dataSource) {
        _dataSource = [NSMutableArray array];
    }
    return _dataSource;
}

- (NSMutableArray *)deleteArray {
    
    if (!_deleteArray) {
        _deleteArray = [NSMutableArray array];
    }
    return _deleteArray;
}

- (void)setup {
    
    self.title = MYLocalizedString(@"ACCOUNT_DOWNLOAD", nil);
    [self rightBarButtonWithImageName:@"删除" selector:@selector(showDeleteView)];
    self.bottomView.hidden = YES;
    
//    @weakify(self);
//    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
//        @strongify(self);
//        [self loadDataSource];
//    }];
    
    [self.totalDeleteBtn setTitle:[NSString localizedStringWithFormat:MYLocalizedString(@"MYDOWNLOAD_DELETE_TOTAL", nil),0] forState:UIControlStateNormal];
    [self.totalSelectBtn setTitle:MYLocalizedString(@"MYDOWNLOAD_DELETE_SELECTALL", nil) forState:UIControlStateNormal];
    [self.totalSelectBtn setTitle:MYLocalizedString(@"MYDOWNLOAD_DELETE_DESELECT", nil) forState:UIControlStateSelected];
    [self.cancelBtn setTitle:MYLocalizedString(@"PUBLIC_CANCEL", nil) forState:UIControlStateNormal];
    
    [self configEmptyDataTableView:self.tableView emptyImageName:@"暂无下载" describe:MYLocalizedString(@"PUBLIC_NODATA_DOWNLOAD", nil) refresh:nil block:nil];
    
    self.tableView.allowsMultipleSelectionDuringEditing = YES;
    
    [self.tableView setThemeStyle:ThemeStyleBlack];
    [self loadDataSource];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeLinemodelState:) name:kDownloadBeginDownNotif object:nil];
}

- (void)changeLinemodelState:(NSNotification *)noti {
    
    NSString *unionid = noti.userInfo[kDownloadNotifLineID];
    DownloadState state = [noti.userInfo[kDownloadState] integerValue];
    
    NSInteger section = 0;
    
    for (LineModel *model in self.dataSource) {
        
        if ([model.unionid isEqualToString:unionid]) {
            
            model.state = state;
            
            @try {
                [self.tableView reloadSections:[NSIndexSet indexSetWithIndex:section] withRowAnimation:UITableViewRowAnimationNone];
            } @catch (NSException *exception) {
                IGLog(@"cdsafasfasdfa %@",exception);
            } @finally {
                break;
            }

        }
        section ++;
    }
}

- (void)loadDataSource {
    
    __block NSArray *dataArray = nil;
    [DownloadListDAO getLineModelListBlock:^(NSArray<LineModel *> *responseDataArray) {
        
        dataArray = responseDataArray;
    }];
    
    self.dataHasLoad = YES;
    [self.tableView.mj_header endRefreshing];
    [self.dataSource removeAllObjects];
    [self.dataSource addObjectsFromArray:dataArray];
    [self.tableView reloadData];
}

- (IBAction)fucAction:(UIButton *)sender {
    
    if (sender.tag == 0) {// 全选
        
        if (sender.selected) {
            
            for (int i = 0; i < self.dataSource.count; i ++) {
                
                NSIndexPath *indexpath = [NSIndexPath indexPathForRow:0 inSection:i];
                
                [self.tableView deselectRowAtIndexPath:indexpath animated:YES];
                
                [self.deleteArray removeAllObjects];
                
            }
            
        } else {
            
            for (int i = 0; i < self.dataSource.count; i ++) {
                
                NSIndexPath *indexpath = [NSIndexPath indexPathForRow:0 inSection:i];
                
                [self.tableView selectRowAtIndexPath:indexpath animated:YES scrollPosition:UITableViewScrollPositionTop];
                
                if (![self.deleteArray containsObject:self.dataSource[i]]) {
                    [self.deleteArray addObject:self.dataSource[i]];
                }
                
            }
        }
        sender.selected = !sender.selected;
        
    } else if (sender.tag == 1) {// 取消
        
        self.tableView.editing = NO;
        self.bottomView.hidden = YES;
        [self.deleteArray removeAllObjects];
        
        
    } else {// 删除
        
        if (self.deleteArray.count == 0) {
            return;
        }
        
        [self deleteDownload];
        
    }
    
    [self.totalDeleteBtn setTitle:[NSString localizedStringWithFormat:MYLocalizedString(@"MYDOWNLOAD_DELETE_TOTAL", nil),self.deleteArray.count] forState:UIControlStateNormal];
}

- (void)showDeleteView {
    
    if (self.dataSource.count == 0 || self.tableView.editing) {
        return;
    }
    
    self.tableView.editing = YES;
    self.bottomView.hidden = NO;
    self.totalSelectBtn.selected = NO;
}

- (void)deleteDownload {
    
    @weakify(self);
    [IGAlertView alertWithTitle:@"" message:MYLocalizedString(@"MYDOWNLOAD_DELETE_COMMIT", nil) cancelButtonTitle:MYLocalizedString(@"PUBLIC_CANCEL", nil) commitBtn:MYLocalizedString(@"PUBLIC_DELETE", nil) commit:^{
        @strongify(self);
        self.tableView.editing = NO;
        self.bottomView.hidden = YES;
        
        [ActivityIndicatorView showHUDAddedTo:self.view];
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            for (LineModel *model in self.deleteArray) {
                [[DownloadManager sharedManager] deleteDownloadWithLineModel:model];
            }
            dispatch_async(dispatch_get_main_queue(), ^ {
                [ActivityIndicatorView hideHUDAddedTo:self.view];
                
                [self.dataSource removeObjectsInArray:self.deleteArray];
                [self.tableView reloadData];
                [self.deleteArray removeAllObjects];
                
                [self.totalDeleteBtn setTitle:[NSString localizedStringWithFormat:MYLocalizedString(@"MYDOWNLOAD_DELETE_TOTAL", nil),self.deleteArray.count] forState:UIControlStateNormal];
            });
        });
    } cancel:nil];
}
#pragma mark -UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return self.dataSource.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return 1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    //    ScenicGuiderListCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    
    AccountDownloadCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    
    LineModel *model = self.dataSource[indexPath.section];
    
    cell.lineModel = model;
    
    return cell;
}

#pragma mark -UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    LineModel *model = self.dataSource[indexPath.section];
    
    if (tableView.editing) {
        
        if (![self.deleteArray containsObject:model]) {
            [self.deleteArray addObject:model];
            
            [self.totalDeleteBtn setTitle:[NSString localizedStringWithFormat:MYLocalizedString(@"MYDOWNLOAD_DELETE_TOTAL", nil),self.deleteArray.count] forState:UIControlStateNormal];
            
            if (self.dataSource.count == self.deleteArray.count) {
                self.totalSelectBtn.selected = YES;
            } else {
                self.totalSelectBtn.selected = NO;
            }
        }
        
        return;
    }
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    [AppManager sharedManager].lineid = model.lineid;
    
    if (model.type.integerValue == 1) {
        
        
        CityTourPlay * vc= [[CityTourPlay alloc] init];
        vc.pageType = 1;
        vc.lineModel = model;
        [self.navigationController pushViewController:vc animated:YES];
        
    }else {
        
        ScenicPlayVC *playVC = [[ScenicPlayVC alloc] init];
        
        playVC.lineModel = model;
        playVC.pageType = 1;
        
        [self.navigationController pushViewController:playVC animated:YES];
    }

}

- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    LineModel *model = self.dataSource[indexPath.section];
    if (tableView.editing) {
        [self.deleteArray removeObject:model];
        [self.totalDeleteBtn setTitle:[NSString localizedStringWithFormat:MYLocalizedString(@"MYDOWNLOAD_DELETE_TOTAL", nil),self.deleteArray.count] forState:UIControlStateNormal];
        
        if (self.dataSource.count == self.deleteArray.count) {
            self.totalSelectBtn.selected = YES;
        } else {
            self.totalSelectBtn.selected = NO;
        }
        return;
    }
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    
    return YES;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    tableView.editing = NO;
    
    LineModel *model = self.dataSource[indexPath.section];
    
    [self.deleteArray addObject:model];
    [self deleteDownload];
    
}

@end
